import {mRequest} from '@/utils/request'
import {btnBlur, downloadHandle, exportHandle, isAuth, isAuthForColumn, specialTypeCheck} from '@/utils'
import {API_DEFAULT_CONFIG} from '@/config'

export default {
  data() {
    return {
      isAuthForColumn: isAuthForColumn,
      isAuth: isAuth,
      pageIndex: 1,
      pageSize: 50,
      totalPage: 0,
      dataList: [],
      dataListSelections: [],
      dataListLoading: false,
      toLastPage: false,
      requestData: null
    }
  },
  computed: {
    imageUrl() {
      return `${API_DEFAULT_CONFIG.baseURL}/pub`
    },
    token() {
      return this.$cookie.get('token')
    }
  },
  methods: {
    searchHandler(additionalOptions) {
      this.pageIndex = 1
      this.getDataList(additionalOptions)
    },
    getDataList(additionalOptions) {
      if (this.toLastPage) {
        this.pageIndex = this.pageIndex - 1
        this.toLastPage = false
      }
      this.dataListLoading = true
      let params = {
        page: this.pageIndex,
        limit: this.pageSize
      }
      if (!this.R.isNil(additionalOptions)) {
        this.R.forEach((key) => {
          this.dataForm[key] = additionalOptions[key]
        }, this.R.keys(additionalOptions))
      }
      const funcAttrList = []

      this.R.forEach((key) => {
        const reg = /(.*)_func/

        if (reg.test(key) && this.dataForm[key] instanceof Function) {
          const re = key.match(reg)

          params[re[1]] = this.dataForm[key]()
          funcAttrList.push(re[1])
        } else if (!funcAttrList.includes(key)) {
          params[key] = this.dataForm[key]

        }
      }, this.R.keys(this.dataForm))
      params = specialTypeCheck(params)

      mRequest(this.listApiName, params, ({data}) => {
        if (data && data.code === 0) {
          this.requestData = data
          this.coumtAmount = data.coumtAmount
          this.dataList = data.page.list
          this.totalPage = data.page.totalCount
        } else {
          this.dataList = []
          this.totalPage = 0
        }
        this.dataListLoading = false
      })
    },
    operationHandle(id, operationStr, apiName) {
      const ids = id ? [id] : this.dataListSelections.map(item => {
        return item[this.primaryKey]
      })
      if (this.R.equals('删除', operationStr)) {
        const deleteNumber = ids.length
        const dataNumber = this.dataList.length

        if (dataNumber <= deleteNumber) {
          this.toLastPage = true
        }
      }
      this.$confirm(`确定对[id=${ids.join(',')}]进行[${id ? operationStr : `批量${operationStr}`}]操作?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          mRequest(apiName, ids, ({data}) => {
            if (data && data.code === 0) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.getDataList()
                }
              })
            } else {
              this.$message.error(data.msg)
            }
          })
        })
        .catch(() => {
        })
    },
    downloadHandle(content, fileName) {
      return downloadHandle(content, fileName)
    },
    deleteHandle(id) {
      return this.operationHandle(id, '删除', this.deleteApiName)
    },
    templateDownloadHandle() {
      return exportHandle(this.templateDownloadApiName)
    },
    printHandle() {
      if (this.R.isNil(this.printFunc)) {
        return
      }
      this.printFunc(this.dataListSelections)
    },
    multiUpdateStatus() {

    },
    plantFuncHandle() {
      if (this.R.isNil(this.exportPlantFunc)) {
        return
      }
      // const ids = id ? [id] : this.dataListSelections.map(item => {
      //   return item[this.primaryKey]
      // })

      this.exportPlantFunc(this.dataListSelections)
    },
    adviceNoteFuncHandle() {
      if (this.R.isNil(this.adviceNoteFunc)) {
        return
      }
      this.adviceNoteFunc(this.dataListSelections)
    },
    multiUpdateStatusFuncHandle() {
      if (this.R.isNil(this.multiUpdateStatusFunc)) {
        return
      }
      this.multiUpdateStatusFunc(this.dataListSelections)
    },


    reorderFuncHandle() {
      if (this.R.isNil(this.reorderFunc)) {
        return
      }
      this.reorderFunc(this.dataListSelections)
    },
    exportHandle() {
      return exportHandle(this.exportApiName, specialTypeCheck(this.dataForm))
    },
    multiAddHandle() {
      let parent = this.$parent

      while (window.R.isNil(parent['addOrUpdateVisible']) && parent.$parent) {
        parent = parent.$parent
      }
      parent.addOrUpdateVisible = true
      this.$nextTick(() => {
        if (!this.R.isNil(parent.$refs.addOrUpdate)) {
          parent.$refs.addOrUpdate.init(null, true)
        }
      })
    },
    deepMultiAddHandle() {
      this.$parent.deepDialogVisible = true
      this.$parent.initMulti()
    },
    addOrUpdateHandle(id, evt) {
      let parent = this.$parent

      while (window.R.isNil(parent['addOrUpdateVisible']) && parent.$parent) {
        parent = parent.$parent
      }
      parent.addOrUpdateVisible = true
      this.$nextTick(() => {
        if (!this.R.isNil(parent.$refs.addOrUpdate)) {
          parent.$refs.addOrUpdate.init(id)
        }
      })
      btnBlur(evt)
    },
    sizeChangeHandle(val) {
      this.pageSize = val
      this.pageIndex = 1
      this.getDataList()
    },
    currentChangeHandle(val) {
      this.$scrollTo()
      this.pageIndex = val
      this.getDataList()
    },
    selectionChangeHandle(val) {
      this.dataListSelections = val
    }
  },
  mounted() {
  },
  created() {
  },
  activated() {
    const searchData = this.R.path(['params', 'searchKey'], this.$route)

    if (!this.R.isNil(searchData)) {
      Object.keys(searchData).forEach(key => {
        const {value, autoCompleteValue} = searchData[key]

        this.dataForm[key] = value
        if (autoCompleteValue) {
          this.dataForm[`autocompleteLabel-${key}`] = autoCompleteValue
        }
      })

      this.$refs.normalForm.$refs.components.forEach(item => {
        item.$refs.component.$forceUpdate()
      })
    }
    this.getDataList()
  },
  filters: {
    formatDate(value) {
      if (value) {
        return value.substring(0, 10)
      }
      return ''
    },
    formatMoney(num) {
      return num ? ((isNaN(parseFloat(num.toString().replace(/,/g, ""))) ? 1 : parseFloat(num.toString().replace(/,/g, "")))).toFixed(2).toString().replace(/(\d)(?=(\d{3})+\.)/g, function($0, $1) {
        return $1 + ",";
      }) : '0.00';
    }
  }
}
